package com.zzyl.serve.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.serve.dao.NursingPlanDto;
import com.zzyl.serve.domain.NursingLevel;
import com.zzyl.serve.domain.NursingProjectPlan;
import com.zzyl.serve.mapper.NursingProjectPlanMapper;
import com.zzyl.serve.vo.NursingPlanVVO;
import com.zzyl.serve.vo.NursingPlanVo;
import com.zzyl.serve.vo.NursingProjectPlanVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.NursingPlanMapper;
import com.zzyl.serve.domain.NursingPlan;
import com.zzyl.serve.service.INursingPlanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 护理计划Service业务层处理
 *
 * @author zzyl
 * @date 2025-10-13
 */
@Service
public class NursingPlanServiceImpl extends ServiceImpl<NursingPlanMapper, NursingPlan> implements INursingPlanService {
    private static final String NURSING_PLAN_ALL = "nursing_plan:all";
    @Autowired
    private NursingPlanMapper nursingPlanMapper;
    @Autowired
    private NursingProjectPlanServiceImpl nursingProjectPlanService;
    @Autowired
    private NursingProjectPlanMapper nursingProjectPlanMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询护理计划
     *
     * @param id 护理计划主键
     * @return 护理计划
     */
    @Override
    public NursingPlanVo selectNursingPlanById(Integer id) {
        //查询护理计划
        NursingPlan byId = this.getById(id);
        //查询中间表
        List<NursingProjectPlan> nprojectPlans = nursingProjectPlanService.list(Wrappers.<NursingProjectPlan>lambdaQuery().eq(NursingProjectPlan::getPlanId, id));
        //封装数据
        //1.把护理计划封装
        NursingPlanVo bean = BeanUtil.toBean(byId, NursingPlanVo.class);
        //3.封装中间表
        List<NursingProjectPlanVo> list = nprojectPlans.stream().map(projectPlan -> {
            NursingProjectPlanVo bean1 = BeanUtil.toBean(projectPlan, NursingProjectPlanVo.class);
            bean1.setProjectId(projectPlan.getProjectId().toString());
            bean1.setExecuteCycle(projectPlan.getExecuteCycle().toString());
            return bean1;
        }).collect(Collectors.toList());
        bean.setProjectPlans(list);
        return bean;
    }

    /**
     * 查询护理计划列表
     *
     * @param nursingPlan 护理计划
     * @return 护理计划
     */
    @Override
    public List<NursingPlan> selectNursingPlanList(NursingPlan nursingPlan) {
        return nursingPlanMapper.selectNursingPlanList(nursingPlan);
    }

    /**
     * 新增护理计划
     *
     * @param dto 护理计划
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertNursingPlan(NursingPlanDto dto) {
        //新增护理计划,需要对数据进行拷贝
        NursingPlan bean = BeanUtil.toBean(dto, NursingPlan.class);
        this.save(bean);
        //新增中间表
        List<NursingProjectPlan> projectPlans = dto.getProjectPlans();
        projectPlans.forEach(projectPlan -> {
            projectPlan.setPlanId(bean.getId());
        });
        boolean baa = nursingProjectPlanService.saveBatch(projectPlans);
        //删除缓存
        deleteRedisCache();
        return baa ? 1 : 0;
    }

    /**
     * 修改护理计划
     *
     * @param dto 护理计划
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateNursingPlan(NursingPlanDto dto) {
        try {


            // 属性拷贝
            NursingPlan nursingPlan = BeanUtil.toBean(dto, NursingPlan.class);

            // 确保ID被正确设置
            nursingPlan.setId(dto.getId().intValue());

            // 先更新护理计划基本信息
            this.updateById(nursingPlan);


            // 获取确定的planId
            Integer planId = dto.getId().intValue();

            // 判断dto中的项目列表不为空，则先删除护理计划与护理项目的关系，然后重新批量添加
            if (dto.getProjectPlans() != null && !dto.getProjectPlans().isEmpty()) {
                // 删除护理计划对应的护理项目列表
                nursingProjectPlanMapper.deleteByPlanId(planId);
                // 批量保存护理计划对应的护理项目列表
                dto.getProjectPlans().forEach(projectPlan -> {
                    projectPlan.setPlanId(planId);
                });
                nursingProjectPlanService.saveBatch(dto.getProjectPlans());
            }
            //删除缓存
            deleteRedisCache();
            return 1;
        } catch (Exception e) {
            throw new RuntimeException("更新护理计划失败: " + e.getMessage(), e);
        }
    }

    /**
     * 删除护理计划
     *
     * @param id 需要删除的护理计划主键集合
     * @return 结果
     */
    @Override
    public int deleteNursingPlanById(Integer id) {
        //TODO 如果此条计划是启用状态，不能删除
        if (this.getById(id).getStatus() == 1) {
            throw new RuntimeException("此计划正在使用中，不能删除");
        }
        //TODO 如果此条计划被绑定了，也不能删除

        // 删除护理计划与护理项目的关系
        nursingProjectPlanMapper.deleteByPlanId(id);
        // 删除护理计划
        //删除缓存
        deleteRedisCache();
        return removeById(id) ? 1 : 0;
    }

    /**
     * 查询所有启用的护理计划
     *
     * @return
     */
    @Override
    public List<NursingPlanVVO> listall() {

        //先用redis查询
        List<NursingPlanVVO> plan = (List<NursingPlanVVO>) redisTemplate.opsForValue().get(NURSING_PLAN_ALL);
        //命中就返回，为命中就查询数据库
        if (CollectionUtils.isNotEmpty(plan)) {
            return plan;
        }
        plan = nursingPlanMapper.listall();
        //存到redis
        redisTemplate.opsForValue().set(NURSING_PLAN_ALL, plan);
//        System.out.println(listall);
        return plan;
    }

    /**
     * 删除缓存的方法，可以直接调用，不需要参数
     */
    private void deleteRedisCache() {
        // 删除缓存
        redisTemplate.delete(NURSING_PLAN_ALL);
    }

}
